﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Xml;
using System.Xml.XPath;
/// <summary>
/// Author: Paul Hanton
/// www.naeborra.com
/// </summary>
public class EntityModelUpdate
{
    private String fileName = @"D:\Backup\我的文档\Visual Studio 2010\Projects\ZhaoPin\ZhaoPin\Recruit.edmx";
    public String XPathPre =
     "//edmx:Edmx/edmx:Runtime/edmx:StorageModels/ns1:Schema/ns1:EntityType[@Name='{0}']/ns1:Property[@Name='{1}']";
    public String[,] Xpaths = 
  { 
   {"EntityType","Property"},
  };
    public String[,] XAttr =
 {
  {"StoreGeneratedPattern","Identity"}
 };
    private XmlReader reader = null;
    private Boolean _changed = false;
    public int ChangedProperty = 0;
    public String Filename
    {
        get
        {
            return fileName;
        }
        set
        {
            this.fileName = value;
        }
    }
    public Boolean DocumentChanged
    {
        get
        {
            return _changed;
        }
    }
    public EntityModelUpdate()
    {
        ChangedProperty = 0;
    }
    public void FixIt()
    {
        _changed = false;
        reader = XmlReader.Create(fileName);
        XmlDocument doc = new XmlDocument();
        try
        {
            doc.Load(reader);
            XPathNavigator navigator = doc.CreateNavigator();

            XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
            manager.AddNamespace("edmx", doc.DocumentElement.NamespaceURI);
            manager.AddNamespace("ns1", @"http://schemas.microsoft.com/ado/2009/02/edm/ssdl");

            for (int i = 0; i < (Xpaths.Length / 2); i++)
            {
                String xp = String.Format(XPathPre, Xpaths[i, 0], Xpaths[i, 1]);
                XmlNode xn = doc.SelectSingleNode(xp, manager);
                if (xn != null)
                {
                    for (int j = 0; j < (XAttr.Length / 2); j++)
                    {
                        XmlAttribute xa = xn.Attributes[XAttr[j, 0]];
                        if (xa == null)
                        {
                            //Add StoreGeneratedPattern="Identity"
                            XmlAttribute newx = doc.CreateAttribute(XAttr[j, 0]);
                            newx.Value = XAttr[j, 1];
                            xn.Attributes.Append(newx);
                            Console.WriteLine("Type:"+xn.ParentNode.Attributes["Name"].Value);
                            ChangedProperty++;
                            _changed = true;
                        }
                    }
                }
            }

        }
        finally
        {
            if (reader != null)
                reader.Close();

            if (_changed)
            {
                XmlWriterSettings ws = new XmlWriterSettings();
                ws.Indent = true;

                String fnameOnly = Path.GetFileNameWithoutExtension(fileName);
                String fnameExt = Path.GetExtension(fileName);
                String DefaultLocation = Path.GetDirectoryName(fileName)+"\\";

                String tempfilename = DefaultLocation + String.Format("{0}_temp{1}", fnameOnly, fnameExt);
                int fTry = 0;
                while (File.Exists(tempfilename))
                {
                    fTry++;
                    tempfilename = DefaultLocation + String.Format("{0}_temp_{2}{1}", fnameOnly, fnameExt, fTry);
                }
                try
                {
                    XmlWriter writer = XmlWriter.Create(tempfilename, ws);
                    try
                    {
                        if (doc != null)
                            doc.Save(writer);
                    }
                    finally
                    {
                        if (writer != null)
                            writer.Close();
                    }
                }
                finally
                {
                    String backupfile = DefaultLocation + String.Format("{0}_backup{1}", fnameOnly, fnameExt);
                    File.Replace(tempfilename, fileName,backupfile);
                    File.Delete(tempfilename);
                    File.Delete(backupfile);
                }
            }
        }
    }
}
